<?php

namespace App\Http\Middleware\Admin;

use App\Models\AdminRole;
use App\Models\Permission;
use App\Models\Role;
use Closure;

class AdminAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request,Closure $next)
    {
    	if(\Auth::check()){

			if(\auth('admin')->user()->status == 0){
				\Auth::guard('admin')->logout();
				return redirect()->route('admin.login')->with('danger','该用户已锁定');
			}

			//查询当前访问的url
			$url =  $request->segment(1) . '/' . $request->segment(2) . '/' . $request->segment(3);

			$roleIds = AdminRole::query()
				->select(\DB::raw('GROUP_CONCAT(role_id) as role_ids'))
				->where('admin_id',\Auth::guard('admin')->id())
				->firstOrFail()
				->toArray();

			$roleModel = new Role();
			//如果用户的角色中，包含超级管理员，也直接去获取所有的菜单列表
			if(in_array('1',explode(',',$roleIds['role_ids'])) || auth('admin')->id() == 1){
				$menu = $roleModel->getMenu('super');
				view()->share('menu',$menu);
				//直接放行
				return $next($request);
			}

			$menu = [];

			if($roleIds){
				//获取所有的权限id
				$allPermissionIds = $roleModel->getRolePermissionIds($roleIds);

				//获得菜单
				$menu = $roleModel->getMenu('admin',$allPermissionIds);
			}

			view()->share('menu',$menu);

			//查询当前url所对应的权限id
			$per_id = Permission::query()->where('route_url',$url)->value('id');

			//判断权限 首页是哪个都可以进的


			//超级管理员 或首页 或退出页 或 用户拥有超级管理员角色 都直接通过
			if($url == 'admin/index/index'  || $url == 'admin/login/logout' || in_array($per_id,$allPermissionIds)){
				return $next($request);
			}else{
				if(request()->ajax()){
					return response()->json(['code'=>403,'msg'=>'此权限暂未开放']);
				}
				abort(403,'此权限暂未开放');
			}
    	}else{
			if(request()->ajax()){
				return response()->json(['code'=>401,'msg'=>'登录状态已失效，请重新登录！']);
			}
			//没有登录就跳转到login
			return redirect()->route('admin.login');
		}
    }
}
